//index.js
//获取应用实例
var app = getApp();
var rootDocment = app.globalData.postUrl;
var last_scroll_position = 0
var new_scroll_position = 0

const listMenu = [{
        name: '红烧猪蹄',
        icon: 'https://i.postimg.cc/hPtShpKh/image.jpg'
    },
    {
        name: '裹凉皮',
        icon: 'https://i.postimg.cc/fLwMQKLc/image.jpg'
    },
    {
        name: '臭豆腐',
        icon: 'https://i.postimg.cc/d0gGWhVc/image.jpg'
    },
    {
        name: '精品凉菜',
        icon: 'https://i.postimg.cc/qR9QCm3n/image.jpg'
    },
    {
        name: '章鱼小丸子',
        icon: 'https://i.postimg.cc/d1XrxLQK/image.jpg'
    },
    {
        name: '梅菜扣肉',
        icon: 'https://i.postimg.cc/43kSnnXx/image.jpg'
    },
    {
        name: '红烧狮子肉',
        icon: 'https://i.postimg.cc/Vk3F4hhG/image.jpg'
    },
    {
        name: '猪肉大葱',
        icon: 'https://i.postimg.cc/s2sMV9Gf/image.jpg'
    }
];
Page({
    data: {
        rootDocment: rootDocment,
        is_official_account: false,
        blockBj: '',
        adShow: false,
        bottomHeight: 0,
        loading: true,
        isShow: true,
        hiddenLoading: false,
        imgUrls: [
            // {
            //   pic:'/images/banner1.jpg'
            // }
        ],
        index_video: '',
        indicatorDots: false,
        autoplay: true,
        interval: 5000,
        duration: 1000,
        topicList: [],
        newGoodsList: [],
        topGoodsList: [],
        hitsGoodsList: [],
        hotGoodsList: [],
        navHeight: app.globalData.navHeight, //导航栏高度
        navTop: app.globalData.navTop, //导航栏距顶部距离
        navObj: app.globalData.navObj, //胶囊的高度
        navObjWid: app.globalData.navObjWid, //胶囊宽度+距右距离
        iphonex: app.globalData.model,
        tabbar: {}, //自定义tab,传给子组件
        swiperCurrent: 0, //当前所在滑块的 index
        lists: [],
        arrLen: 5, //分组数 最大值10,当为奇数时候，默认加1提示为偶数
        oneLen: 5, //一行展示多少
        videoCoverImg: 'http://img5.imgtn.bdimg.com/it/u=1672477765,2527992874&fm=26&gp=0.jpg',
        // 滑动比例计算
        slideWidth: '', //滑块宽
        slideLeft: 0, //滑块位置
        totalLength: '', //当前滚动列表总长
        slideShow: false, //滑块是否显示
        slideRatio: '', //滑块比例
        // 渲染数据
        dataList: [{
                name: '品牌介绍',
                icon: 'https://lhs.tann.cc/upload/images/new/tabs_1.png',
                url: 'brandInt/index',
                isTab: false,
            },
            {
                name: '礼品区',
                icon: 'https://lhs.tann.cc/upload/images/new/tabs_2.png',
                url: 'newcomer/index',
                isTab: false,
            },
            {
                name: '会员专区',
                icon: 'https://lhs.tann.cc/upload/images/new/tabs_3.png',
                isTab: true,
                url: 'user/vip'
            },
            {
                name: '小皇优选',
                icon: 'https://lhs.tann.cc/upload/images/new/tabs_4.png',
                isTab: false,
                url: 'Preferred/index'
            },
        ],
        newProduct: [],
        hotList: [],
        write_style: '',
        is_write_style: true,
        is_date: false,
        is_ggr: false,


        topOpacity: 0,
    },

    onShow: function () {
        var that = this;

        this.setData({
            is_shop: wx.getStorageSync('is_shop') || 0,
        })

        that.getJg()

        if (app.globalData.userInfo.userID) {
            app.login(function (userInfo) {
                that.setData({
                    userInfo: userInfo
                });
                that.getJg()
            });
        }

        //初始化
        that.setSlideData();
        that.setNewGoodsData();
        that.setTopGoodsData();
        that.setTopicData();
        that.setHotGoodsData();
        that.setOrderGoodsData()

    },

    onLoad: function (opt) {
        let is_vip = wx.getStorageSync('is_vip') ? wx.getStorageSync('is_vip') : 0
        console.log('会员日', this.getWeekByDate(new Date()));
        // if (this.getWeekByDate(new Date()) && is_vip) {
        //     this.setData({
        //         is_date: true
        //     })
        // }

        const startTime = new Date(2025, 2, 15, 0, 0, 0); // 2025-03-15 00:00:00
        const endTime = new Date(2025, 2, 20, 0, 0, 0); // 2025-03-20 00:00:00

        // 判断逻辑
        let isActive = () => {
            const now = new Date();
            return now >= startTime && now < endTime;
        }
        this.setData({
            // is_ggr: isActive(),
            is_official_account: true
        })

        // if (!is_vip) {
        //   this.setData({
        //     adShow: true
        //   })
        // } else {
        //   this.setData({
        //     adShow: false
        //   })
        // }

        setTimeout(() => {
            this.setData({
                loading: false
            })
        }, 3000)
        var that = this;
        //获取分销ID并缓存
        if (opt.scene) {
            var scene = decodeURIComponent(opt.scene);

            wx.setStorageSync('pid', scene);
        }

        // 底部tabber
        app.editTabbar();
        // 菜单轮播
        this.getData()
        this.setAd()
        this.data_vip_list()
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        if (wx.getStorageSync('shop_name') == '') {
            this.setData({
                shop_name: '榴皇树'
            })
        } else {
            this.setData({
                shop_name: wx.getStorageSync('shop_name')
            })
        }
        this.setData({
            bottomHeight: app.globalData.bottomHeight
        })

    },
    //获取当前是几号 26号会员日弹窗
    getWeekByDate(dates) {
        var currentDate = new Date(); // 创建一个Date对象，表示当前时间
        var day = currentDate.getDate(); // 获取当前日期，即几号
        if (day == '26') {
            return true
        } else {
            return false
        }
        // if (isActive() == true) {
        //   return true
        // } else if (day == '26') {
        //   return true
        // } else {
        //   return false
        // }



        // let show_day = new Array('7', '1', '2', '3', '4', '5', '6');
        // let date = new Date(dates);
        // date.setDate(date.getDate());
        // let day = date.getDay();
        // return show_day[day];
    },
    //  周三会员日弹窗关闭
    onClickDateHide() {
        this.setData({
            is_date: false
        })
    },
    // 跳转到周三会员日列表
    memberDaySure() {
        console.log('跳转到周三会员日列表');
        wx.navigateTo({
            // url: `/pages/goods/detail?id=${this.data.vip_list[0].id}&is_member_day=${1}`,
            url: '/pages/specialList/index?type=member_day',
        })
        // vip_list
    },


    goVip() {
        app.redirect('vipCore/index')
    },
    getJg() {
        let is_shop = this.data.is_shop
        let data = [{
                name: '品牌介绍',
                icon: 'https://lhs.tann.cc/upload/images/new/tabs_1.png',
                url: 'brandInt/index',
                isTab: false,
            },
            {
                name: '礼品区',
                icon: 'https://lhs.tann.cc/upload/images/new/tabs_2.png',
                url: 'newcomer/index',
                isTab: false,
            },
            {
                name: '会员专区',
                icon: 'https://lhs.tann.cc/upload/images/new/tabs_3.png',
                isTab: true,
                url: 'user/vip'
            },
            {
                name: '小皇优选',
                icon: 'https://lhs.tann.cc/upload/images/new/tabs_4.png',
                isTab: false,
                url: 'Preferred/index'
            }
        ]

        console.log('-------------------', is_shop)
        console.log('-------------------', is_shop >= 1)

        if (is_shop >= 1) {
            data[2].name = '进货专区'
            data[2].url = 'hhrCore/index'
            data[2].isTab = false
            this.setData({
                dataList: data
            })
        } else {
            data[2].name = '会员专区'
            data[2].url = 'user/vip'
            data[2].isTab = false
            this.setData({
                dataList: data
            })
        }

        console.log(this.data.dataList)
    },

    // 菜单数据
    getData() {
        let dataList = listMenu,
            {
                arrLen,
                oneLen
            } = this.data,
            lists = [],
            isOdd = (arrLen % 2) === 0;
        if (!isOdd && arrLen > 5) arrLen = arrLen + 1;
        arrLen = arrLen > 10 ? 10 : arrLen;
        oneLen = arrLen > 5 ? arrLen / 2 : arrLen;
        for (var i = 0; i < dataList.length; i += arrLen) {
            lists.push(dataList.slice(i, i + arrLen));
        }
        this.setData({
            lists,
            arrLen,
            oneLen,
        })
    },


    /**
     * 轮播图切换
     * @param {*} e 
     */
    swiperChange: function (e) {
        if (e.detail.source == "touch" || e.detail.source == "autoplay") {
            this.setData({
                swiperCurrent: e.detail.current
            })
        }
    },

    //下拉刷新
    onPullDownRefresh: function () {
        this.setSlideData();
        this.setNewGoodsData();
        this.setTopGoodsData();
        this.setTopicData();
        this.setHotGoodsData();
        this.setOrderGoodsData()
        wx.stopPullDownRefresh();
    },

    onPageScroll: function (e) {
        // Do something when page scroll
        // console.log('我动了吗')
        // console.log(e, '滑动');
        var that = this
        let write_style = that.data.write_style
        last_scroll_position = e.scrollTop;
        if (new_scroll_position < last_scroll_position && last_scroll_position > 50) {
            that.setData({
                write_style: 'slideUp'
            })

        } else {
            that.setData({
                write_style: 'slideDown'
            })
        }
        new_scroll_position = last_scroll_position;
        let floatingFrame = this.selectComponent('#floatingFrame'); // 页面获取自定义组件实例
        floatingFrame.isHide(); // 通过实例调用组件事件
        if (that.data.write_style != write_style && that.data.write_style == 'slideDown') {
            // console.log('我动了吗')
            that.setData({
                is_write_style: true
            })
        }
        if (that.data.write_style != write_style && that.data.write_style == 'slideUp') {
            that.setData({
                is_write_style: false
            })
        }

        if (e.scrollTop > 50) {
            let opacity = e.scrollTop / 300;
            opacity = opacity > 1 ? 1 : opacity;
            this.setData({
                topOpacity: opacity
            });
        } else {
            this.setData({
                topOpacity: 0
            });
        }
    },

    //初始化幻灯片
    setSlideData: function () {
        // wx.showLoading({
        //   mask:true,
        //   title: '加载中',
        // })
        var that = this;
        var paraArr = new Array();
        paraArr['size'] = "5";
        paraArr['type'] = "3";
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_ads',
            data: {
                size: paraArr['size'],
                type: paraArr['type'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                // wx.hideLoading()
                that.setData({
                    imgUrls: res.data.data
                });
            }
        })
    },

    onReady: function () {
        this.videoContext = wx.createVideoContext('myVideo')
    },

    bindplay: function (e) {
        this.setData({
            isShow: false
        })
        this.videoContext.play();
        console.log('play')
    },

    //初始化幻灯片
    setAd: function () {
        var that = this;
        var paraArr = new Array();
        let user_id = wx.getStorageSync('user_id3') ? wx.getStorageSync('user_id3') : ''
        // var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api/llgn/getAds',
            data: {
                user_id: user_id

            },
            method: 'GET',
            header: {},
            success: function (res) {
                wx.setStorageSync('kefu', res.data.data.kefu)
                that.setData({
                    // isShow:false,
                    adImgUrls: res.data.data,
                    blockBj: res.data.data.home_pop,
                    index_video: res.data.data.video
                });
            }
        })
    },

    onClickHide() {
        this.setData({
            // isShow:false,
            adShow: false
        });
    },

    onClickGer() {
        console.log(1111111);
        this.setData({
            // isShow:false,
            is_ggr: false
        });
    },

    //初始化新品
    setNewGoodsData: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['size'] = "2";
        paraArr['type'] = "new";
        paraArr['user_id'] = wx.getStorageSync('user_id3') || 0;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_goods',
            data: {
                size: paraArr['size'],
                type: paraArr['type'],
                user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                that.setData({
                    newProduct: res.data.data
                });
                // that.setData({
                //   newGoodsList: res.data.data
                // });
            }
        })
    },

    //人气推荐
    setOrderGoodsData: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['size'] = "4";
        paraArr['type'] = "hot";
        paraArr['order'] = "hits";
        paraArr['user_id'] = wx.getStorageSync('user_id3') || 0;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_goods',
            data: {
                size: paraArr['size'],
                type: paraArr['type'],
                order: paraArr['order'],
                user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                console.log(res, '人气推荐')
                that.setData({
                    hotList: [...res.data.data]
                });
                // that.setData({
                //   hitsGoodsList: [...res.data.data]
                // });
            }
        })
    },

    //VIP推荐
    setTopGoodsData: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['size'] = "6";
        paraArr['type'] = "vip";
        paraArr['user_id'] = wx.getStorageSync('user_id3') || 0;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_goods',
            data: {
                size: paraArr['size'],
                type: paraArr['type'],
                user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                console.log(res, '商品信息')
                that.setData({
                    topGoodsList: [...res.data.data]
                });
            }
        })
    },

    //初始化促销专区
    setTopicData: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['size'] = "1";
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_topic',
            data: {
                size: '1',
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                that.setData({
                    topicList: res.data.data
                });
            }
        })
    },

    //初始化为您推荐
    setHotGoodsData: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['size'] = "16";
        paraArr['type'] = "pt";
        paraArr['user_id'] = wx.getStorageSync('user_id3') || 0;
        var sign = app.signature(paraArr);
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_goods',
            data: {
                size: paraArr['size'],
                type: paraArr['type'],
                user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                console.log(res, '....')
                that.setData({

                    hotGoodsList: res.data.data,
                    hiddenLoading: true
                });
            }
        })
    },

    //周三会员商品
    data_vip_list() {
        var that = this;
        var paraArr = new Array();
        paraArr['size'] = "8";
        paraArr['type'] = 'member_day';
        paraArr['user_id'] = wx.getStorageSync('user_id3') || 0;
        // paraArr['user_id'] = 'member_day';
        // member_day
        // 99_vip
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_goods',
            data: {
                size: paraArr['size'],
                type: paraArr['type'],
                user_id: paraArr['user_id'],
                // user_id: paraArr['user_id'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                that.setData({
                    vip_list: res.data.data
                });

            }
        })
    },

    //点击幻灯片
    showSlide: function (e) {
        let item = e.currentTarget.dataset.item

        console.log(wx.getStorageInfoSync("user_id3"))

        if (!app.globalData.userInfo.userID) {
            app.login();
            return
        }

        if (!app.globalData.userInfo.mobile) {
            wx.navigateTo({
                url: '/pages/shouji/shouji',
            })

            return
        }

        if (item.kind == 1) {
            let url = item.url
            if (!url || url == '#') return;
            // 原始带转义的 URL
            const originalUrl = url;

            // 替换 &amp; 为 &（注意替换所有实例）
            const fixedUrl = originalUrl.replace(/&amp;/g, "&");
            console.log(' 原始带转义的 URL', fixedUrl, );
            app.redirect(fixedUrl);
        } else if (item.kind == 2) {
            app.redirect('goods/detail', 'id=' + item.detail);
        }
        //let url = item.
        // var url = e.currentTarget.dataset.url
        // if (!url || url == '#') return;
        // app.redirect(url);
    },

    //点击金刚区
    funJump(e) {
        let item = e.currentTarget.dataset.item
        let url = item.url
        console.log(url)
        if (!url || url == '#') return;
        if (item.isTab) {
            app.gotaburl(url)
        } else {
            app.redirect(url);
        }

    },

    goNavBtn(e) {
        let type = e.currentTarget.dataset.type
        if (type == 1) {
            wx.switchTab({
                url: '/pages/vipCore/index',
            })
        } else if (type == 2) {
            wx.showToast({
                title: '文化馆尚未开放，请耐心等待',
                icon: 'none'
            })
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        console.log(res);
        var that = this;
        return {
            title: '榴皇树',
            path: '/pages/index/index?scene=' + wx.getStorageSync('user_id3')
        }
    },

    onShareTimeline: function (res) {
        console.log(res);
        var that = this;
        return {
            title: '榴皇树',
            path: '/pages/index/index?scene=' + wx.getStorageSync('user_id3')
            // imageUrl: that.data.detail['pic']
        }
    },
    onHide() {
        this.setData({
            is_official_account: false
        })
    }
})